package com.ojoin.ojoin.eb_spider.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ojoin.ojoin.eb_spider.service.catchdata.SupplierYHDDataCatchServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.MD5FileUtil;
import com.ojoin.trade.common.utils.UUIDUtils;
import com.ojoin.trade.common.utils.VerityCodeUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import com.ojoin.trade.common.utils.json.JSONUtils;

/**
 * 
 * @author cqz qq:6199401 email:cheqinzho@qq.com
 * 
 */
@SuppressWarnings("unchecked")
public class DMV3 {
	/** 主机 */
	static final String GETDOMAINARRY = "http://dama3.hyslt.com";
	/** 测试接口验证码路径 */
	// static final String IMGPATH = "D:/1.jpg";
	/** 用户名 */
	static final String USERNAME = "doubao";
	/** 密码 */
	static final String PASSWORD = "doubao123456";
	/** 最大请求次数 */
	static final int TIMES = 10;

	/** 设置编码 */
	static final String CODE = "UTF-8";

	private static Logger log = LoggerFactory
			.getLogger(DMV3.class);
	
	public static void main(String[] args) throws Exception {

		String domain = getDoMainArryAndValidUser();

		byte[] buf = VerityCodeUtils.getBytes(java.net.URLDecoder
				.decode(DMV3.class.getResource("1.jpg").getFile()));

		String yzm_id = add(domain, buf);

		//System.out.println(getResult(domain, yzm_id));
	}

	public static Map getVerifyCode(byte[] in) throws Exception {

		String domain = getDoMainArryAndValidUser();
 
		String yzm_id = add(domain, in);
		
		int i = 0;
		boolean flag = false ;
		Map rm = new HashMap();
		while(i<6 && !flag){ 
			i++; 
			rm = getResult(domain,yzm_id);
			WaitUtil.waitTimeSeconds(6);
			LogUtils.info(log, "验证码获取等待时间-- %s",6*i);
			flag = (boolean)rm.get("result");
		}
		
		if(flag){
			rm.put("domain", domain);
			rm.put("yzm_id", yzm_id);
			return  rm;
		}else {
			LogUtils.error(log, rm.toString());
			throw new BusinessException("获取验证码出错");
		}

	}

	// 获取服务器
	@SuppressWarnings("unchecked")
	public static String getDoMainArryAndValidUser() throws Exception {
		HttpClient client = new HttpClient();
		String result = "";
		PostMethod postMethod;
		postMethod = new PostMethod(GETDOMAINARRY
				+ "/api.php?mod=yzm&act=server");
		postMethod.addParameter("user_name", USERNAME);
		postMethod.addParameter("user_pw", getBASE64(PASSWORD));
		postMethod.addParameter("mac", CodeGenerator.getStrMac());
		postMethod.addParameter("key", CodeGenerator.getKey());
		postMethod.addParameter("submit", "%CC%ED+%BC%D3");
		client.executeMethod(postMethod);
		result = new String(postMethod.getResponseBody(), "gbk");
		Map rm = JSONUtils.parseObject(result, Map.class);
		return (String) rm.get("data");

	}

	// 上传验证码
	@SuppressWarnings("deprecation")
	public static String add(String domain, byte[] f) throws Exception {

		HttpClient client = new HttpClient();
		String result = "";

		MultipartPostMethod filePost = new MultipartPostMethod("http://"
				+ domain + "/api.php?mod=yzm&act=add");
		ByteArrayPartSource bs = new ByteArrayPartSource("verifyCodeImage", f);
		FilePart cbFile = new FilePart("upload", bs);
		cbFile.setContentType("image/pjpeg");
		filePost.addParameter("mac", CodeGenerator.getStrMac());
		filePost.addParameter("key", CodeGenerator.getKey());
		filePost.addParameter("user_name", USERNAME);
		filePost.addParameter("user_pw", getBASE64(PASSWORD));

		filePost.addParameter("yzmtype_mark", "0");
		filePost.addParameter("yzm_minlen", "4");
		filePost.addParameter("yzm_maxlen", "6");
		// todo 待开发者自己填写
		// filePost.addParameter("zztool_token", "xxx");

		String fileName = UUIDUtils.create() + ".jpg";
		filePost.addParameter("filename", fileName);
		filePost.addPart(cbFile);

		client.getHttpConnectionManager().getParams()
				.setConnectionTimeout(10000);
		client.executeMethod(filePost);
		result = getTranCode(filePost.getResponseBodyAsString(), CODE);
		Map rm = JSONUtils.parseObject(result, Map.class);
		return String.valueOf(rm.get("data"));

	}

	// 作者分成接口
	@SuppressWarnings("deprecation")
	public static String add4Dev(String domain, File f) throws Exception {

		HttpClient client = new HttpClient();
		String result = "";

		MultipartPostMethod filePost = new MultipartPostMethod("http://"
				+ domain + "/api.php?mod=yzm&act=add");
		FilePart cbFile = new FilePart("upload", f);
		cbFile.setContentType("image/pjpeg");
		filePost.addParameter("mac", CodeGenerator.getStrMac());
		filePost.addParameter("key", CodeGenerator.getKey());
		filePost.addParameter("user_name", USERNAME);
		filePost.addParameter("user_pw", getBASE64(PASSWORD));

		filePost.addParameter("yzmtype_mark", "0");
		filePost.addParameter("yzm_minlen", "4");
		filePost.addParameter("yzm_maxlen", "4");
		// todo 待开发者自己填写
		// filePost.addParameter("zztool_token", "xxx");

		String fileName = MD5FileUtil.getFileMD5String(f) + ".jpg";
		filePost.addParameter("filename", fileName);
		filePost.addPart(cbFile);

		client.getHttpConnectionManager().getParams()
				.setConnectionTimeout(10000);
		client.executeMethod(filePost);
		result = getTranCode(filePost.getResponseBodyAsString(), CODE);
		Map rm = JSONUtils.parseObject(result, Map.class);
		return (Integer) rm.get("data") + "";
	}

	// 查询点数
	@SuppressWarnings("deprecation")
	public static String point(String domain) throws Exception {
		HttpClient client = new HttpClient();
		String result = "";
		MultipartPostMethod filePost = new MultipartPostMethod("http://"
				+ domain + "/api.php?mod=yzm&act=point");
		filePost.addParameter("mac", CodeGenerator.getStrMac());
		filePost.addParameter("key", CodeGenerator.getKey());
		filePost.addParameter("user_name", USERNAME);
		filePost.addParameter("user_pw", getBASE64(PASSWORD));
		client.getHttpConnectionManager().getParams()
				.setConnectionTimeout(10000);
		client.executeMethod(filePost);
		result = getTranCode(filePost.getResponseBodyAsString(), CODE);
		return result;
	}

	// 获取结果
	@SuppressWarnings("deprecation")
	public static Map getResult(String domain, String yzm_id)
			throws Exception {
		HttpClient client = new HttpClient();
		String result = "";
		MultipartPostMethod filePost = new MultipartPostMethod("http://"
				+ domain + "/api.php?mod=yzm&act=result");
		filePost.addParameter("mac", CodeGenerator.getStrMac());
		filePost.addParameter("key", CodeGenerator.getKey());
		filePost.addParameter("yzm_id", yzm_id);
		client.getHttpConnectionManager().getParams()
				.setConnectionTimeout(10000);
		client.executeMethod(filePost);
		result = getTranCode(filePost.getResponseBodyAsString(), CODE);
		Map rm = JSONUtils.parseObject(result, Map.class);

		return rm;
		
		
	}

	// 报错
	@SuppressWarnings("deprecation")
	public static String yzm_error(String domain, String yzm_id)
			throws Exception {
		HttpClient client = new HttpClient();
		String result = "";
		MultipartPostMethod filePost = new MultipartPostMethod("http://"
				+ domain + "/api.php?mod=dmuser&act=yzm_error");
		filePost.addParameter("mac", CodeGenerator.getStrMac());
		filePost.addParameter("key", CodeGenerator.getKey());
		filePost.addParameter("yzm_id", yzm_id);
		client.getHttpConnectionManager().getParams()
				.setConnectionTimeout(10000);
		client.executeMethod(filePost);
		result = getTranCode(filePost.getResponseBodyAsString(), CODE);

		return result;
	}

	// 将 s 进行 BASE64 编码
	public static String getBASE64(String s) {
		if (s == null)
			return null;
		return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
	}

	public static String getTranCode(String str) {
		if (System.getProperty("os.name").contains("Windows")) {
			byte[] data;
			try {
				data = str.getBytes("ISO8859-1");
				return new String(data, "GBK");
			} catch (UnsupportedEncodingException e) {
				return str;
			}
		} else {
			return str;
		}

	}

	public static String getTranCode(String str, String code) {
		if (System.getProperty("os.name").contains("Windows")) {
			byte[] data;
			try {
				data = str.getBytes("ISO8859-1");
				return new String(data, code);
			} catch (UnsupportedEncodingException e) {
				return str;
			}
		} else {
			return str;
		}

	}
}
